import React, {Component, createRef} from 'react';
import {FinishBar, ProgressBarContainer, Slider} from "../style/ProgressBar.css";

class ProgressBar extends Component {
    constructor(props)   {
        super(props);
        this.state={
            dragProgress:this.props.progress || 0,
            drag:false
        }
        this._drag = false;
        this._dragProgress = 0;
        this.progressBarRef =createRef()
    }
    get progress(){
        return (this.state.drag?this._dragProgress:this.props.progress) || 0
    }
    render() {
        return (
            <ProgressBarContainer ref={this.progressBarRef} onMouseDown={(e)=>this.mouseDownHandle(e)}>
                {/*{this.finishBar}*/}
                <FinishBar progress={this.progress} />
                <Slider progress={this.progress}/>
            </ProgressBarContainer>
        );
    }

    setDragProgress(e){
        let {left, right} = this.progressBarRef.current.getBoundingClientRect()
        let cursorX = e.clientX
        let p;
        if (cursorX < left) p = 0;
        else if (right < cursorX) p = 1;
        else p = (cursorX - left) / (right - left)
        this._dragProgress = p;
        this.setState(()=>({
            dragProgress:this._dragProgress
        }))

    }

    mouseDownHandle = (e)=>{
        this._drag = true;
        this.setState({
            drag:this._drag
        })
        this.setDragProgress(e);
        document.addEventListener("mousemove",this.mouseMoveHandle)
        document.addEventListener("mouseup",this.mouseUpHandle)

    }
    mouseUpHandle = (e)=>{
        this._drag = false;
        this.setState({drag:this._drag})
        this.setDragProgress(e)
        this.props.setprogress(this._dragProgress);
        document.removeEventListener("mousemove",this.mouseMoveHandle)
        document.removeEventListener("mouseup",this.mouseUpHandle)
    }
    mouseMoveHandle=(e)=>{
        if(this.state.drag) {
            this.setDragProgress(e)
        }
    }
}

export default ProgressBar;